package com.shouer.doc;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.shouer.doc.message.AppTxtMsgMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.rong.push.RongPushClient;
import io.rong.push.notification.PushNotificationMessage;

/**
 * Created by ZXL on 2016/11/16.
 */

public class NotificationInterface {

    private static HashMap<String, List<PushNotificationMessage>> messageCache = new HashMap();
    private static int ORDER_NOTIFICATION_ID=500;
    private static int NOTIFICATION_ID = 6000;
    private static int PUSH_SERVICE_NOTIFICATION_ID = 2000;
    private static int VOIP_NOTIFICATION_ID = 3000;
    private static final int NEW_NOTIFICATION_LEVEL = 11;
    private static final int PUSH_REQUEST_CODE = 200;
    private static boolean isInNeglectTime = false;
    private static final int NEGLECT_TIME = 1000;
    private static Timer timer = new Timer();

    public NotificationInterface() {
    }

    public static void sendOrderNotification(Context context,String content)
    {
        NotificationInterface.SoundType soundType = NotificationInterface.SoundType.DEFAULT;
        String title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
        Notification notification = createNotification(context, title, null, content, soundType);
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        if(notification != null) {
            nm.notify(ORDER_NOTIFICATION_ID, notification);
        }
    }

    public static void sendOrderNotification(Context context, PushNotificationMessage message)
    {
        NotificationInterface.SoundType soundType = NotificationInterface.SoundType.DEFAULT;
        String title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
        Notification notification = createNotification(context, title, null, getOrderNotificationContent(message), soundType);
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        if(notification != null) {
            nm.notify(ORDER_NOTIFICATION_ID, notification);
        }
    }

    public static void sendAppTxtMsgNotification(Context context, String content)
    {
        NotificationInterface.SoundType soundType = NotificationInterface.SoundType.DEFAULT;
        String title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
        Intent intent = new Intent();
        intent.setData(Uri.parse("rong://com.shouer.doc/healthrecord"));
        PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0);
        Notification notification = createNotification(context, title, pi, content, soundType);
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        if(notification != null) {
            nm.notify(ORDER_NOTIFICATION_ID, notification);
        }
    }

    public static String getOrderNotificationContent(PushNotificationMessage message)
    {
        String pushContent=message.getPushData();
        try {
            JSONObject jsonObject=new JSONObject(pushContent);
            return jsonObject.getString("content");
        } catch (JSONException e) {
            e.printStackTrace();
            return "平台有新订单了";
        }
    }

    public static void sendNotification(Context context, PushNotificationMessage message) {
        Log.i(NotificationInterface.class.getSimpleName(),"sendNotification");
        if(messageCache == null) {
            messageCache = new HashMap();
        }

        RongPushClient.ConversationType conversationType = message.getConversationType();
        String objName = message.getObjectName();
        String content = "";
        boolean isMulti = false;
        short requestCode = 200;
        NotificationInterface.SoundType soundType = NotificationInterface.SoundType.DEFAULT;
        if(!TextUtils.isEmpty(objName) && conversationType != null) {
            if(isInNeglectTime) {
                soundType = NotificationInterface.SoundType.SILENT;
            }

            String title;
            int notificationId;
            if(!conversationType.equals(RongPushClient.ConversationType.SYSTEM) && !conversationType.equals(RongPushClient.ConversationType.PUSH_SERVICE)) {

                if(!objName.equals("RC:VCInvite") && !objName.equals("RC:VCModifyMem") && !objName.equals("RC:VCHangup")) {
                    title = getNotificationTitle(context);
                    content=message.getPushContent();
                    notificationId = NOTIFICATION_ID;
                    ++NOTIFICATION_ID;
                } else {
                    if(objName.equals("RC:VCHangup")) {
                        removeNotification(context, VOIP_NOTIFICATION_ID);
                        return;
                    }

                    notificationId = VOIP_NOTIFICATION_ID;
                    soundType = NotificationInterface.SoundType.VOIP;
                    requestCode = 400;
                    title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
                    content = message.getPushContent();
                }
            } else {
                title = message.getPushTitle();
                if(TextUtils.isEmpty(title)) {
                    title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
                }

                content = message.getPushContent();
                notificationId = PUSH_SERVICE_NOTIFICATION_ID;
                requestCode = 300;
                ++PUSH_SERVICE_NOTIFICATION_ID;
            }

            PendingIntent var14 = createPendingIntent(context, message, requestCode, isMulti);
            Notification notification = createNotification(context, title, var14, content, soundType);
            NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            if(notification != null) {
                nm.notify(notificationId, notification);
            }

            if(!isInNeglectTime) {
                timer.schedule(new TimerTask() {
                    public void run() {
                        NotificationInterface.isInNeglectTime = false;
                    }
                }, 1000L);
                isInNeglectTime = true;
            }

        }
    }

    public static void removeAllNotification(Context context) {
        messageCache.clear();
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancelAll();
        NOTIFICATION_ID = 1000;
    }

    public static void removeAllPushNotification(Context context) {
        messageCache.clear();
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(NOTIFICATION_ID);
        nm.cancel(VOIP_NOTIFICATION_ID);
    }

    public static void removeAllPushServiceNotification(Context context) {
        NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

        for(int i = PUSH_SERVICE_NOTIFICATION_ID; i >= 1000; --i) {
            nm.cancel(i);
        }

        PUSH_SERVICE_NOTIFICATION_ID = 2000;
    }

    public static void removeNotification(Context context, int notificationId) {
        if(notificationId >= 0) {
            if(notificationId >= NOTIFICATION_ID && notificationId < PUSH_SERVICE_NOTIFICATION_ID) {
                messageCache.clear();
            }

            NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            nm.cancel(notificationId);
        }
    }

    private static PendingIntent createPendingIntent(Context context, PushNotificationMessage message, int requestCode, boolean isMulti) {
        Intent intent = new Intent();
        intent.setAction("io.rong.push.intent.MESSAGE_CLICKED");
        intent.putExtra("message", message);
        intent.putExtra("isMulti", isMulti);
        intent.setPackage(context.getPackageName());
        return PendingIntent.getBroadcast(context, requestCode, intent, 134217728);
    }

    private static String getNotificationContent(Context context) {
        String rc_notification_new_msg = context.getResources().getString(context.getResources().getIdentifier("rc_notification_new_msg", "string", context.getPackageName()));
        String rc_notification_new_plural_msg = context.getResources().getString(context.getResources().getIdentifier("rc_notification_new_plural_msg", "string", context.getPackageName()));
        String content;
        if(messageCache.size() == 1) {
            Collection count = messageCache.values();
            List collection = (List)count.iterator().next();
            PushNotificationMessage i$ = (PushNotificationMessage)collection.get(0);
            if(collection.size() == 1) {
                content = i$.getPushContent();
            } else {
                content = String.format(rc_notification_new_msg, new Object[]{i$.getTargetUserName(), Integer.valueOf(collection.size())});
            }
        } else {
            int count1 = 0;
            Collection collection1 = messageCache.values();

            List msg;
            for(Iterator i$1 = collection1.iterator(); i$1.hasNext(); count1 += msg.size()) {
                msg = (List)i$1.next();
            }

            content = String.format(rc_notification_new_plural_msg, new Object[]{Integer.valueOf(messageCache.size()), Integer.valueOf(count1)});
        }

        return content;
    }

    private static String getNotificationTitle(Context context) {
        String title;
        if(messageCache.size() == 1) {
            Collection collection = messageCache.values();
            List msg = (List)collection.iterator().next();
            PushNotificationMessage notificationMessage = (PushNotificationMessage)msg.get(0);
            title = notificationMessage.getTargetUserName();
        } else {
            title = (String)context.getPackageManager().getApplicationLabel(context.getApplicationInfo());
        }

        return title;
    }

    private static Notification createNotification(Context context, String title, PendingIntent pendingIntent, String content, NotificationInterface.SoundType soundType) {
        String tickerText = context.getResources().getString(context.getResources().getIdentifier("rc_notification_ticker_text", "string", context.getPackageName()));
        if(TextUtils.isEmpty(content)) {
            content = getNotificationContent(context);
        }

        Notification notification;
        if(Build.VERSION.SDK_INT < 11) {
            try {
                notification = new Notification(context.getApplicationInfo().icon, tickerText, System.currentTimeMillis());
                Class smallIcon = Notification.class;
                Method isLollipop = smallIcon.getMethod("setLatestEventInfo", new Class[]{Context.class, CharSequence.class, CharSequence.class, PendingIntent.class});
                isLollipop.invoke(notification, new Object[]{context, title, content, pendingIntent});
                notification.flags = 16;
                notification.defaults = -1;
            } catch (Exception var14) {
                var14.printStackTrace();
                return null;
            }
        } else {
            boolean isLollipop1 = Build.VERSION.SDK_INT >= 21;
            int smallIcon1 = context.getResources().getIdentifier("notification_small_icon", "drawable", context.getPackageName());
            if(smallIcon1 <= 0 || !isLollipop1) {
                smallIcon1 = context.getApplicationInfo().icon;
            }

            byte defaults = -1;
            Uri sound = null;
            if(soundType.equals(NotificationInterface.SoundType.SILENT)) {
                defaults = 4;
            }

            if(soundType.equals(NotificationInterface.SoundType.VOIP)) {
                defaults = 6;
                sound = RingtoneManager.getDefaultUri(1);
            }

            BitmapDrawable bitmapDrawable = (BitmapDrawable)context.getApplicationInfo().loadIcon(context.getPackageManager());
            Bitmap appIcon = bitmapDrawable.getBitmap();
            Notification.Builder builder = new Notification.Builder(context);
            builder.setLargeIcon(appIcon);
            builder.setSmallIcon(smallIcon1);
            builder.setTicker(tickerText);
            builder.setContentTitle(title);
            builder.setContentText(content);
            builder.setContentIntent(pendingIntent);
            builder.setAutoCancel(true);
            builder.setSound(sound);
            builder.setDefaults(defaults);
            notification = builder.getNotification();
        }

        return notification;
    }

    private static enum SoundType {
        DEFAULT(0),
        SILENT(1),
        VOIP(2);

        int value;

        private SoundType(int v) {
            this.value = v;
        }
    }
}
